package version3.part1.Client.serviceCenter.ZKWatcher;

import lombok.AllArgsConstructor;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import version3.part1.Client.Cache.ServiceCache;


@AllArgsConstructor
public class watchZK {
    private CuratorFramework client;
    private ServiceCache cache;

    public void watchToUpdate(String path){
        // CuratorCache 用于监视Zookeeper中路径的变化
        CuratorCache curatorCache = CuratorCache.build(client, path);
        curatorCache.listenable().addListener(new CuratorCacheListener() {
            /**
             * @param type 事件类型
             * @param childData 节点更新前的状态、数据
             * @param childData1 节点更新后的状态、数据
             */
            @Override
            public void event(Type type, ChildData childData, ChildData childData1) {
                switch (type){
                    case NODE_CREATED :
                        // 节点创建, childData 为空,childData1 为新创建的节点
                        String[] pathList_create = parsePath(childData1);
                        // 分割出的节点会有一个根节点，然后是服务名称节点，然后是服务地址节点
                        // 如果长度小于等于2，那么就没有新的服务地址
                        if(pathList_create.length <= 2) break;
                        else{
                            String serviceName = pathList_create[1];
                            String serviceAddress = pathList_create[2];
                            cache.addService(serviceName, serviceAddress);
                        }
                        break;
                    case NODE_DELETED :
                        // 节点删除, childData 为删除的节点,childData1 为空
                        String[] pathList_delete = parsePath(childData);
                        if(pathList_delete.length <= 2) break;
                        else{
                            String serviceName = pathList_delete[1];
                            String serviceAddress = pathList_delete[2];
                            cache.removeService(serviceName, serviceAddress);
                        }
                        break;
                    case NODE_CHANGED:
                        // 节点更新, childData 为更新前的节点,childData1 为更新后的节点
                        String[] oldPathList = parsePath(childData);
                        String[] newPathList = parsePath(childData1);
                        cache.updateService(oldPathList[1], oldPathList[2], newPathList[2]);
                        break;
                    default :
                        break;
                }
            }
        });
        // 启动CuratorCache,开启监听
        curatorCache.start();
    }

    private String[] parsePath(ChildData childData){
        String[] pathList = childData.getPath().split("/");
        return pathList;
    }
}
